
import { getToken, setToken, removeToken } from '@/utils/auth'

import { postLogin } from '@/api/user'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  DELETE_TOKEN: (state, token) => {
    state.token = ''
    removeToken()
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login, 要写上下文
  async login({ commit }, loginForm) {
    const { mobile, password } = loginForm
    try {
      const res = await postLogin(mobile, password)
      console.log('res', res)
      commit('SET_TOKEN', res)
    } catch (er) {
      console.log(er, 'er')
    }
  },
  logout(context) {
    context.commit('DELETE_TOKEN')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

